<template>
  <div class="monitoring-dashboard">
    <div class="page-header">
      <h1>数据库性能监控</h1>
      <div class="header-actions">
        <el-select v-model="selectedConnection" placeholder="选择数据库连接" style="width: 200px; margin-right: 10px;">
          <el-option
            v-for="conn in connectionList"
            :key="conn.id"
            :label="conn.name"
            :value="conn.id"
          />
        </el-select>
        <el-button type="primary" @click="collectMetrics" :disabled="!selectedConnection">
          <el-icon><Refresh /></el-icon>
          收集指标
        </el-button>
      </div>
    </div>

    <!-- 实时指标卡片 -->
    <div class="metrics-cards" v-if="currentMetrics">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="metric-card">
            <div class="metric-content">
              <div class="metric-icon cpu">
                <el-icon><Cpu /></el-icon>
              </div>
              <div class="metric-info">
                <div class="metric-value">{{ currentMetrics.cpu_usage?.toFixed(1) }}%</div>
                <div class="metric-label">CPU使用率</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="metric-card">
            <div class="metric-content">
              <div class="metric-icon memory">
                <el-icon><MemoryCard /></el-icon>
              </div>
              <div class="metric-info">
                <div class="metric-value">{{ currentMetrics.memory_usage?.toFixed(1) }}%</div>
                <div class="metric-label">内存使用率</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="metric-card">
            <div class="metric-content">
              <div class="metric-icon disk">
                <el-icon><FolderOpened /></el-icon>
              </div>
              <div class="metric-info">
                <div class="metric-value">{{ currentMetrics.disk_usage?.toFixed(1) }}%</div>
                <div class="metric-label">磁盘使用率</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="metric-card">
            <div class="metric-content">
              <div class="metric-icon connection">
                <el-icon><Connection /></el-icon>
              </div>
              <div class="metric-info">
                <div class="metric-value">{{ currentMetrics.connection_count }}</div>
                <div class="metric-label">活跃连接数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据库特定指标 -->
    <div class="database-metrics" v-if="currentMetrics">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card>
            <template #header>
              <span>数据库信息</span>
            </template>
            <div class="info-item">
              <span class="info-label">表数量:</span>
              <span class="info-value">{{ currentMetrics.table_count }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">数据库大小:</span>
              <span class="info-value">{{ currentMetrics.database_size_mb }}MB</span>
            </div>
            <div class="info-item">
              <span class="info-label">响应时间:</span>
              <span class="info-value">{{ currentMetrics.response_time?.toFixed(2) }}ms</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card>
            <template #header>
              <span>查询统计</span>
            </template>
            <div class="info-item">
              <span class="info-label">活跃查询:</span>
              <span class="info-value">{{ currentMetrics.active_queries }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">慢查询:</span>
              <span class="info-value">{{ currentMetrics.slow_queries }}</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card>
            <template #header>
              <span>性能摘要</span>
            </template>
            <div class="info-item" v-if="performanceSummary">
              <span class="info-label">平均CPU:</span>
              <span class="info-value">{{ performanceSummary.avg_cpu?.toFixed(1) }}%</span>
            </div>
            <div class="info-item" v-if="performanceSummary">
              <span class="info-label">平均内存:</span>
              <span class="info-value">{{ performanceSummary.avg_memory?.toFixed(1) }}%</span>
            </div>
            <div class="info-item" v-if="performanceSummary">
              <span class="info-label">平均响应时间:</span>
              <span class="info-value">{{ performanceSummary.avg_response_time?.toFixed(2) }}ms</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 历史数据图表 -->
    <div class="charts-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>监控历史</span>
            <div class="time-range-selector">
              <el-radio-group v-model="timeRange" @change="fetchMonitoringHistory">
                <el-radio-button label="1">1小时</el-radio-button>
                <el-radio-button label="6">6小时</el-radio-button>
                <el-radio-button label="24">24小时</el-radio-button>
                <el-radio-button label="168">7天</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </template>
        
        <div class="chart-placeholder" v-if="!monitoringHistory.length">
          <el-empty description="暂无监控数据" />
        </div>
        
        <div class="charts-grid" v-else>
          <div class="chart-item">
            <h4>CPU使用率趋势</h4>
            <div class="simple-chart">
              <div 
                v-for="(item, index) in monitoringHistory" 
                :key="index"
                class="chart-bar"
                :style="{ height: `${item.cpu_usage}%`, backgroundColor: getColorByValue(item.cpu_usage, 80) }"
              ></div>
            </div>
          </div>
          
          <div class="chart-item">
            <h4>内存使用率趋势</h4>
            <div class="simple-chart">
              <div 
                v-for="(item, index) in monitoringHistory" 
                :key="index"
                class="chart-bar"
                :style="{ height: `${item.memory_usage}%`, backgroundColor: getColorByValue(item.memory_usage, 85) }"
              ></div>
            </div>
          </div>
          
          <div class="chart-item">
            <h4>连接数趋势</h4>
            <div class="simple-chart">
              <div 
                v-for="(item, index) in monitoringHistory" 
                :key="index"
                class="chart-bar"
                :style="{ 
                  height: `${Math.min(item.connection_count / maxConnections * 100, 100)}%`, 
                  backgroundColor: getColorByValue(item.connection_count, 50) 
                }"
              ></div>
            </div>
          </div>
          
          <div class="chart-item">
            <h4>响应时间趋势</h4>
            <div class="simple-chart">
              <div 
                v-for="(item, index) in monitoringHistory" 
                :key="index"
                class="chart-bar"
                :style="{ 
                  height: `${Math.min(item.response_time / maxResponseTime * 100, 100)}%`, 
                  backgroundColor: getColorByValue(item.response_time, 1000) 
                }"
              ></div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 告警列表 -->
    <div class="alerts-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>活跃告警</span>
            <el-button type="text" @click="fetchActiveAlerts">刷新</el-button>
          </div>
        </template>
        
        <el-table :data="activeAlerts" style="width: 100%">
          <el-table-column prop="alert_type" label="告警类型" width="150" />
          <el-table-column prop="severity" label="严重程度" width="100">
            <template #default="scope">
              <el-tag :type="getSeverityColor(scope.row.severity)">
                {{ getSeverityText(scope.row.severity) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="message" label="告警信息" show-overflow-tooltip />
          <el-table-column prop="current_value" label="当前值" width="100" />
          <el-table-column prop="threshold_value" label="阈值" width="100" />
          <el-table-column prop="created_at" label="创建时间" width="180" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="text" size="small" @click="resolveAlert(scope.row)">
                解决
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Refresh, Cpu, MemoryCard, FolderOpened, Connection 
} from '@element-plus/icons-vue'
import api from '@/utils/api'

// 响应式数据
const selectedConnection = ref(null)
const timeRange = ref('24')
const currentMetrics = ref(null)
const performanceSummary = ref(null)
const connectionList = ref([])
const monitoringHistory = ref([])
const activeAlerts = ref([])

// 计算属性
const maxConnections = computed(() => {
  if (!monitoringHistory.value.length) return 100
  return Math.max(...monitoringHistory.value.map(item => item.connection_count))
})

const maxResponseTime = computed(() => {
  if (!monitoringHistory.value.length) return 1000
  return Math.max(...monitoringHistory.value.map(item => item.response_time))
})

// 方法
const fetchConnectionList = async () => {
  try {
    const response = await api.get('/database/connections/')
    if (response.data.success) {
      let data = response.data.data
      
      if (Array.isArray(data)) {
        connectionList.value = data.filter((conn: any) => conn.is_active)
      } else if (data && Array.isArray(data.results)) {
        connectionList.value = data.results.filter((conn: any) => conn.is_active)
      }
      
      // 自动选择第一个连接
      if (connectionList.value.length > 0 && !selectedConnection.value) {
        selectedConnection.value = connectionList.value[0].id
      }
    }
  } catch (error) {
    console.error('获取连接列表失败:', error)
  }
}

const collectMetrics = async () => {
  if (!selectedConnection.value) {
    ElMessage.warning('请先选择数据库连接')
    return
  }

  try {
    const response = await api.post('/database/monitoring/collect/', {
      connection_id: selectedConnection.value
    })

    if (response.data.success) {
      currentMetrics.value = response.data.data
      ElMessage.success('监控指标收集成功')
      
      // 收集指标后刷新历史数据
      await fetchMonitoringHistory()
      await fetchPerformanceSummary()
    }
  } catch (error) {
    console.error('收集监控指标失败:', error)
    ElMessage.error('收集监控指标失败')
  }
}

const fetchMonitoringHistory = async () => {
  if (!selectedConnection.value) return

  try {
    const response = await api.get('/database/monitoring/history/', {
      params: {
        connection_id: selectedConnection.value,
        hours: timeRange.value
      }
    })

    if (response.data.success) {
      monitoringHistory.value = response.data.data
    }
  } catch (error) {
    console.error('获取监控历史失败:', error)
  }
}

const fetchPerformanceSummary = async () => {
  if (!selectedConnection.value) return

  try {
    const response = await api.get('/database/monitoring/summary/', {
      params: {
        connection_id: selectedConnection.value,
        hours: timeRange.value
      }
    })

    if (response.data.success) {
      performanceSummary.value = response.data.data
    }
  } catch (error) {
    console.error('获取性能摘要失败:', error)
  }
}

const fetchActiveAlerts = async () => {
  if (!selectedConnection.value) return

  try {
    const response = await api.get('/database/alerts/', {
      params: {
        connection_id: selectedConnection.value,
        is_resolved: false
      }
    })

    if (response.data.success) {
      let data = response.data.data
      
      if (Array.isArray(data)) {
        activeAlerts.value = data
      } else if (data && Array.isArray(data.results)) {
        activeAlerts.value = data.results
      }
    }
  } catch (error) {
    console.error('获取活跃告警失败:', error)
  }
}

const resolveAlert = async (alert: any) => {
  try {
    const response = await api.post(`/database/alerts/${alert.id}/resolve_alert/`)
    if (response.data.success) {
      ElMessage.success('告警已解决')
      await fetchActiveAlerts()
    }
  } catch (error) {
    console.error('解决告警失败:', error)
    ElMessage.error('解决告警失败')
  }
}

const getColorByValue = (value: number, threshold: number) => {
  if (value >= threshold) return '#f56c6c'
  if (value >= threshold * 0.8) return '#e6a23c'
  return '#67c23a'
}

const getSeverityColor = (severity: string) => {
  const colors: Record<string, string> = {
    'low': 'info',
    'medium': 'warning',
    'high': 'danger',
    'critical': 'danger'
  }
  return colors[severity] || 'info'
}

const getSeverityText = (severity: string) => {
  const texts: Record<string, string> = {
    'low': '低',
    'medium': '中',
    'high': '高',
    'critical': '严重'
  }
  return texts[severity] || severity
}

// 监听连接变化
watch(selectedConnection, async (newConnection) => {
  if (newConnection) {
    await fetchMonitoringHistory()
    await fetchPerformanceSummary()
    await fetchActiveAlerts()
  }
})

// 生命周期
onMounted(async () => {
  await fetchConnectionList()
  if (selectedConnection.value) {
    await fetchMonitoringHistory()
    await fetchPerformanceSummary()
    await fetchActiveAlerts()
  }
})
</script>

<style scoped>
.monitoring-dashboard {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.metrics-cards {
  margin-bottom: 20px;
}

.metric-card {
  cursor: default;
}

.metric-content {
  display: flex;
  align-items: center;
}

.metric-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: white;
  font-size: 20px;
}

.metric-icon.cpu { background: #409eff; }
.metric-icon.memory { background: #67c23a; }
.metric-icon.disk { background: #e6a23c; }
.metric-icon.connection { background: #f56c6c; }

.metric-info {
  flex: 1;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.metric-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.database-metrics {
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.info-label {
  color: #909399;
}

.info-value {
  font-weight: bold;
  color: #303133;
}

.charts-section {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.time-range-selector {
  display: flex;
  align-items: center;
}

.chart-placeholder {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.chart-item {
  text-align: center;
}

.chart-item h4 {
  margin: 0 0 16px 0;
  color: #303133;
}

.simple-chart {
  height: 120px;
  display: flex;
  align-items: end;
  justify-content: space-between;
  padding: 0 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background: #fafafa;
}

.chart-bar {
  width: 8px;
  min-height: 2px;
  border-radius: 2px;
  transition: all 0.3s;
}

.alerts-section {
  margin-bottom: 20px;
}
</style>
